#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* extraído del enunciado */
void ed(uint8_t *data, size_t ndata, const uint8_t *key, size_t nkey)
{
    uint8_t i = 0, j = 0, s[256];
    do { s[i] = i; } while (++i);
    do {
        j += s[i] + key[i % nkey];
        i - j && (s[i] ^= s[j], s[j] ^= s[i], s[i] ^= s[j]);
    } while (++i);
    j = 0;
    while (ndata--) {
        i++; j += s[i];
        i - j && (s[i] ^= s[j], s[j] ^= s[i], s[i] ^= s[j]);
        *data++ ^= s[(s[i] + s[j]) & 0xff];
    }
}

void get_file_data(uint8_t **data, size_t *data_len, const char *path)
{
    FILE *fp = fopen(path, "rb");
    fseek(fp, 0, SEEK_END);
    *data_len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    *data = malloc(*data_len);
    fread(*data, 1, *data_len, fp);
    fclose(fp);
}

int test_key(uint8_t *data, size_t data_len, const char *key)
{
    size_t key_len = strlen(key);
    ed(data, data_len, (const uint8_t *)key, key_len);
    for (size_t i = 0; i < data_len; i++)
        if (data[i] > 127)
            return 0;
    return 1;
}

int main(int argc, char *argv[])
{
    uint8_t *file_contents = NULL;
    size_t file_size = 0;
    if (argc != 3)
        return 1;
    get_file_data(&file_contents, &file_size, argv[1]);
    if (test_key(file_contents, file_size, argv[2]))
        printf("OK\n");
    else
        printf("FAIL\n");
    free(file_contents);
    return 0;
}
